﻿/*******************************************************************************
 * Copyright © 2016-2020 北京网非科技有限公司 版权所有
 * Author: 北京网非科技有限公司
 * Description: 网非快速开发平台NET
 * Website：http://www.wfdot.com
*********************************************************************************/
using CubicFWNet.Common;
using CubicFWNet.Data.SystemManage;
using CubicFWNet.Data.SystemManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CubicFWNet.Application.SystemManage
{
    public class ItemApp
    {
        private readonly ItemRepository _itemRepository = new ItemRepository();
        private readonly ItemCategoryRepository _itemCategoryRepository = new ItemCategoryRepository();


        public IEnumerable<Item> GetItems(Guid categoryId)
        {
            return _itemRepository.IQueryable(a => a.CategoryId == categoryId || categoryId == Guid.Empty).OrderByDescending(a=>a.SortNo);
        }
        public Item GetItem(Guid itemId)
        {
            return _itemRepository.FindEntity(itemId);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Result:int</returns>
        public ResponseResult Delete(Guid id)
        {
            var del = _itemRepository.FindEntity(id);
            if (del == null)
                return new ResponseResult { Status = ResultType.error.ToString(), Message = "未找到该数据", Data = id };
            _itemRepository.Delete(del);
            return new ResponseResult { Status = ResultType.success.ToString(), Data = id };
        }

        public int AddOrUpdate(Item item)
        {
            if (item.Id == Guid.Empty)
            {
                item.Id = Guid.NewGuid();
                return _itemRepository.Insert(item);
            }
            else
            {
                return _itemRepository.Update(item);
            }
        }

        public IEnumerable<ItemCategory> GetItemCategory()
        {
            return _itemCategoryRepository.IQueryable();
        }

        public Guid GetItemCategoryId(string categoryName)
        {
            if(string.IsNullOrWhiteSpace(categoryName))
            {
                return Guid.Empty;
            }
            else
            {
                var expression = ExtLinq.True<ItemCategory>();
                expression = expression.And(t => t.Name == categoryName);
                return _itemCategoryRepository.IQueryable(expression).Select(i=>i.Id).FirstOrDefault();
            }    
        }
    }
}
